package com.kmxd.ams.infra.utils;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.ImmutableList;

import java.util.List;

public class StrMatchUtil {

  /**
   * 按sunday算法，按关键词匹配字符串
   *
   * @param text 字符串
   * @param pattern 关键词
   * @return 是否包含
   */
  public static boolean sundayMatch(String text, String pattern) {
    boolean res = false;
    int tLen = text.length();
    int pLen = pattern.length();
    // 使用更大的数组以支持Unicode字符
    int[] shiftTable = new int[65536];

    for (int i = 0; i < shiftTable.length; i++) {
      // 默认的字符偏移值设为模式长度+1
      shiftTable[i] = pLen + 1;
    }

    for (int i = 0; i < pLen; i++) {
      char pChar = pattern.charAt(i);
      // 对于中文字符，最小的偏移值为1
      shiftTable[pChar] = Math.max(1, pLen - i);
    }

    int tIndex = 0;
    while (tIndex <= tLen - pLen) {
      int pIndex = 0;

      while (pIndex < pLen && text.charAt(tIndex + pIndex) == pattern.charAt(pIndex)) {
        pIndex++;
      }

      if (pIndex == pLen) {
        return true;
      }

      if (tIndex + pLen >= tLen) {
        break;
      }

      char nextChar = text.charAt(tIndex + pLen);
      tIndex += shiftTable[nextChar];
    }

    return res;
  }

  public static boolean sundayMatch(String text, List<String> keywords) {
    if (CharSequenceUtil.isBlank(text)) {
      return false;
    }

    if (ObjectUtil.isEmpty(keywords)) {
      return false;
    }

    for (String keyword : keywords) {
      boolean flag = sundayMatch(text, keyword);
      if (flag) {
        return flag;
      }
    }
    return false;
  }

  public static void main(String[] args) {
    String text = "我花朵祖国的!";
    String pattern = "花朵";

    boolean flag = sundayMatch(text, ImmutableList.of("a", "的"));

    if (flag) {
      System.out.println("匹配到");
    } else {
      System.out.println("未匹配到");
    }
  }
}
